<template>
  <div>
    <div style="display: flex; justify-content: space-around; align-items: center">
      <el-dropdown @command="selectState">
        <el-button type="primary" v-text="state" style="width: 100px"></el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="全部状态">全部状态</el-dropdown-item>
          <el-dropdown-item command="上架">上架</el-dropdown-item>
          <el-dropdown-item command="下架">下架</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown @command="selectType">
        <el-button type="primary" v-text="typeName" style="width: 100px"></el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="全部类型">全部类型</el-dropdown-item>
          <el-dropdown-item v-for="i in typeData" :key="i.id" :command="i.typeName">{{i.typeName}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <h3>菜品列表</h3>
      <div style="width: 300px">
        <el-input placeholder="根据菜品名称或菜品类型搜索" v-model="inputValue" @keyup.enter="search">
          <el-button slot="append" icon="el-icon-search" @click="search()"></el-button>
        </el-input>
      </div>
      <el-button type="primary" @click="resetting">重置</el-button>
    </div>
    <el-table class="table" :data="dishData" style="width: 100%">
      <el-table-column prop="photo" label="图片"  align="center">
        <template slot-scope="scope">
          <el-image :src="url + scope.row.photo"  style="width: 100px"/>
        </template>
      </el-table-column>
      <el-table-column prop="dishName" label="名称"  align="center"></el-table-column>
      <el-table-column prop="typeName" label="类型" align="center"></el-table-column>
      <el-table-column prop="price" sortable label="价格" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.price / 100}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="grade" sortable label="评分" align="center">
        <template slot-scope="scope">
          <div class="block">
            <el-rate
              v-model="scope.row.grade"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}" v-if="scope.row.grade != null">
            </el-rate>
            <div v-if="scope.row.grade == null">暂无评分</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态"  align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.state === 1 ? '已上架' : '已下架' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button @click="editDish(scope.row)" type="text" style="margin-right: 10px">
            编辑
          </el-button>
          <el-drawer
            title="修改菜品"
            :visible.sync="edit_dish"
            size="25%"
            style="text-align: center; font-size: 15px">
            <div style="text-align: left">
              <el-form ref="form" :model="dishForm" label-width="80px">
                <el-form-item label="菜品名称">
                  <el-input class="input" v-model="dishForm.dishName" style="width: 75%"></el-input>
                </el-form-item>
                <el-form-item label="菜品价格">
                  <el-input class="input" v-model="dishForm.price" placeholder="单位：分" style="width: 75%"></el-input>
                </el-form-item>
                <el-form-item label="菜品类型">
                  <el-select v-model="dishForm.typeName" placeholder="菜品类型">
                    <el-option v-for="i in typeData" :key="i.typeId" :label="i.typeName" :value="i.typeName"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="菜品状态">
                  <el-select v-model="dishForm.state">
                    <el-option label="下架" value='下架'></el-option>
                    <el-option label="上架" value='上架'></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="菜品图片">
                  <el-upload
                    action="https://jsonplaceholder.typicode.com/posts/"
                    list-type="picture-card"
                    name="dishPhoto"
                    :http-request="upload"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateDish()">修改</el-button>
                  <el-button @click="cancel">取消</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-drawer>
          <el-button @click="getAssessData(scope.row.id)" type="text" style="margin-right: 10px">
            查看评论
          </el-button>
          <el-drawer
            title="菜品评论"
            :visible.sync="assess"
            :append-to-body="true"
            size="40%"
            style="text-align: center; font-size: 15px">
            <el-divider></el-divider>
            <div v-for="i in assessData">
              <div style="display: flex; justify-content: left">
                <div style="width: 20%;">
                  <div><img :src="url + i.photo" alt="" style="width: 60px; border-radius: 50%; margin-top: 10px"></div>
                  <div style="margin-top: 20px"><el-button type="danger" icon="el-icon-delete" circle @click="deleteAssess(i.orderId, i.dishId)"></el-button></div>
                </div>
                <div style="width: 75%; text-align: left">
                  <h2 style="display: block">{{i.username}}</h2>
                  <p>{{ i.content }}</p>
                  <div style="display: flex; justify-content: space-between">
                    <div class="block">
                      <el-rate
                        v-model="i.grade"
                        disabled
                        show-score
                        text-color="#ff9900"
                        score-template="{value}">
                      </el-rate>
                    </div>
                    <span style="margin-right: 40px">{{i.time}}</span>
                  </div>
                </div>
              </div>
              <el-divider></el-divider>
            </div>
          </el-drawer>
          <el-button @click="deleteDish(scope.row.id)" type="text">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button class="edit_type" @click="edit_type = true" type="success" icon="el-icon-s-fold" circle>
      <el-drawer
        title="菜品类型"
        :direction="'ltr'"
        :append-to-body="true"
        :visible.sync="edit_type"
        size="30%"
        style="text-align: center; font-size: 15px">
        <div>
          <el-input class="input" v-model="addTypeName" style="width: 30%"></el-input>
          <el-button @click="addType()" style="background-color:#3d7eec; color: white">添加</el-button>
          <el-table class="table" :data="typeData">
            <el-table-column prop="typeName" label="类型名" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button @click="deleteType(scope.row.id)" type="text" v-if="scope.row.typeName !== '未设置'">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-drawer>
    </el-button>
    <el-button class="new_dish" @click="newDish()" type="primary" icon="el-icon-plus" circle>
      <el-drawer
        title="新增菜品"
        :direction="'ltr'"
        :append-to-body="true"
        :visible.sync="new_dish"
        size="25%"
        style="text-align: center; font-size: 15px">
        <div style="text-align: left">
          <el-form ref="form" :model="dishForm" label-width="80px">
            <el-form-item label="菜品名称">
              <el-input class="input" v-model="dishForm.dishName" style="width: 75%"></el-input>
            </el-form-item>
            <el-form-item label="菜品价格">
              <el-input class="input" v-model="dishForm.price" placeholder="单位：分" style="width: 75%"></el-input>
            </el-form-item>
            <el-form-item label="菜品类型">
              <el-select v-model="dishForm.typeName" placeholder="菜品类型">
                <el-option v-for="i in typeData" :key="i.typeId" :label="i.typeName" :value="i.typeName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="菜品状态">
              <el-select v-model="dishForm.state">
                <el-option label="下架" value='下架'></el-option>
                <el-option label="上架" value='上架'></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="菜品图片">
              <el-upload
                action="https://jsonplaceholder.typicode.com/posts/"
                list-type="picture-card"
                name="dishPhoto"
                :http-request="upload"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addDish()">添加</el-button>
              <el-button @click="cancel">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>
    </el-button>
    <el-button-group>
      <el-button type="primary" @click="firstPage">首页</el-button>
      <el-button type="primary" icon="el-icon-arrow-left" @click="beforePage">上一页</el-button>
      <el-button type="primary" @click="nextPage">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
      <el-button type="primary" @click="lastPage">尾页</el-button>
    </el-button-group>
  </div>
</template>

<script>
export default {
  name: 'AdminDish',
  data () {
    return {
      assess: false,
      edit_type: false,
      edit_dish: false,
      new_dish: false,
      dialogVisible: false,
      new_type: false,
      dialogImageUrl: '',
      dishData: [],
      typeData: [],
      assessData: [],
      typeName: '全部类型',
      state: '全部状态',
      inputValue: '',
      dishForm: {
        id: 0,
        dishName: '',
        price: '',
        state: '下架',
        typeName: '未设置'
      },
      addTypeName: '',
      photo: null,
      url: this.$url,
      pIndex: 1,
      pSize: 6,
      pCount: 1
    }
  },
  mounted () {
    if (sessionStorage.getItem('phone') !== null) {
      if (sessionStorage.getItem('is_admin') === '1') {
        this.getDishData()
        this.getTypeData()
      } else {
        this.$message.error('您不是管理员!')
        this.$router.push('/customer/customerDish')
      }
    }
  },
  methods: {
    firstPage() {
      if (this.pIndex <= 1) {
        this.$message.error("当前已经在首页了！")
      } else {
        this.pIndex = 1;
        this.getDishData();
      }
    },
    beforePage() {
      if (this.pIndex <= 1) {
        this.$message.error("当前已经在首页了！")
      } else {
        this.pIndex -= 1;
        this.getDishData();
      }
    },
    nextPage() {
      if (this.pIndex >= this.pCount) {
        this.$message.error("当前已经在末页了！");
      } else {
        this.pIndex = parseInt(this.pIndex) + 1;
        this.getDishData();
      }
    },
    lastPage() {
      if (this.pIndex >= this.pCount) {
        this.$message.error("当前已经在末页了！");
      } else {
        this.pIndex = this.pCount;
        this.getDishData();
      }
    },
    resetting () {
      this.typeName = '全部类型'
      this.state = '全部状态'
      this.inputValue = ''
      this.search()
    },
    cancel () {
      this.new_dish = false;
      this.edit_dish = false;
    },
    selectType (command) {
      this.typeName = command
      this.search()
    },
    selectState (command) {
      this.state = command
      this.search()
    },
    search() {
      // 获取菜品列表，修改了筛选参数，需要重置页数
      this.pIndex = 1
      let tmp1 = this.state
      let tmp2 = this.typeName
      let tmp3 = this.inputValue
      if (tmp1 === '全部状态') {
        tmp1 = null
      } else if (tmp1 === '上架') {
        tmp1 = 1
      } else if (tmp1 === '下架') {
        tmp1 = 0
      }
      if (tmp2 === '全部类型') {
        tmp2 = null
      }
      if (tmp3 === '') {
        tmp3 = null
      }
      // 用户根据类型筛选和搜索框，获取菜品列表
      this.$request.post('/dish/admin/getlist', {
        "state": tmp1,
        "typeName": tmp2,
        "inputValue": tmp3,
        'pIndex': this.pIndex,
        'pSize': this.pSize
      }).then((result) => {
        if (result.code === 200) {
          this.dishData = result.data.dishList
          this.pCount = result.data.pageCount
        } else {
          this.$message.error('获取菜品列表失败!')
        }
      })
    },
    getDishData () {
      // 获取菜品列表，不需要重置页数
      let tmp1 = this.state
      let tmp2 = this.typeName
      let tmp3 = this.inputValue
      if (tmp1 === '全部状态') {
        tmp1 = null
      } else if (tmp1 === '上架') {
        tmp1 = 1
      } else if (tmp1 === '下架') {
        tmp1 = 0
      }
      if (tmp2 === '全部类型') {
        tmp2 = null
      }
      if (tmp3 === '') {
        tmp3 = null
      }
      this.$request.post('/dish/admin/getlist', {
        "state": tmp1,
        "typeName": tmp2,
        "inputValue": tmp3,
        'pIndex': this.pIndex,
        'pSize': this.pSize
      }).then((result) => {
        if (result.code === 200) {
          this.dishData = result.data.dishList
          this.pCount = result.data.pageCount
        } else if (result.code === 302) {
        } else {
          this.$message.error('获取菜品列表失败!')
        }
      })
    },
    getTypeData () {
      this.$request.get('/type/getlist').then((result) => {
        if (result.code === 200) {
          this.typeData = result.data
        } else {
          this.$message.error('获取类型列表失败!')
        }
      })
    },
    newDish() {
      this.dishForm.dishName = ''
      this.dishForm.price = ''
      this.dishForm.typeName = '未设置'
      this.dishForm.state = '下架'
      this.new_dish = true
    },
    addDish () {
      if (this.dishForm.dishName === '') {
        this.$message.error('请输入菜品名!')
        return
      }
      if (this.dishForm.price === '') {
        this.$message.error('请输入菜品价格!')
        return;
      }
      let price = parseInt(this.dishForm.price);
      if (isNaN(price)) {
        this.$message.error('价格只能为数字!')
        return;
      }
      let state = this.dishForm.state;
      if (state === '上架') {
        state = 1;
      } else {
        state = 0;
      }
      let typeId = this.dishForm.typeName;
      for (let i of this.typeData) {
        if (typeId === i.typeName) {
          typeId = i.id;
          break;
        }
      }
      this.$request.post('/dish/admin/add', {
        "dishName": this.dishForm.dishName,
        "price": this.dishForm.price,
        "typeId": typeId,
        "state": state
      }).then((result) => {
        if (result.code === 200 && result.data !== 0) {
          this.uploadPhoto(result.data)
          this.resetting()
          this.$message.success('新增菜品成功!')
        } else {
          this.$message.error('新增菜品失败!')
        }
      })
    },
    upload (param) {
      this.photo = param.file
    },
    uploadPhoto(dishId) {
      // 校验图片的合法性
      if (this.photo == null) {
        return;
      }
      let type = this.photo.type;
      const flg1 = !(type === 'image/jpeg' || type === 'image/png')
      const flg2 = this.photo.size / 1024 / 1024 > 1
      if (flg1) {
        this.$alert('上传头像图片只能是 JPG 或 PNG 格式！')
        return;
      }
      if (flg2) {
        this.$alert('上传头像图片大小不能超过 1MB！')
        return;
      }

      const formData = new FormData()
      formData.append('dishId', dishId)
      formData.append('photo', this.photo)
      this.$request({
        method: 'post',
        url: '/dish/admin/photo',
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        data: formData
      }).then(result => {
        if (result.code === 200 && result.data === 1) {
          this.getDishData()
        } else if (result.code === -1) {
          this.$message.error(result.msg)
        } else {
          this.$message.error('图片上传失败!')
        }
      })
      this.photo = null;
    },
    editDish (dish) {
      this.dishForm = JSON.parse(JSON.stringify(dish))
      if (this.dishForm.state === 1) {
        this.dishForm.state = '上架'
      } else {
        this.dishForm.state = '下架'
      }
      this.edit_dish = true
    },
    updateDish () {
      if (this.dishForm.dishName === '') {
        this.$message.error('请输入菜品名!')
        return;
      }
      if (this.dishForm.price === '') {
        this.$message.error('请输入菜品价格!')
        return;
      }
      let price = parseInt(this.dishForm.price);
      if (isNaN(price)) {
        this.$message.error('价格只能为数字!')
        return;
      }
      let state = this.dishForm.state;
      if (state === '上架') {
        state = 1;
      } else {
        state = 0;
      }
      let typeId = this.dishForm.typeName;
      for (let i of this.typeData) {
        if (typeId === i.typeName) {
          typeId = i.id;
          break;
        }
      }
      this.$request.post('/dish/admin/update', {
        "id": this.dishForm.id,
        "dishName": this.dishForm.dishName,
        "price": this.dishForm.price,
        "typeId": typeId,
        "state": state
      }).then((result) => {
        if (result.code === 200 && result.data === 1) {
          this.uploadPhoto(this.dishForm.id)
          this.resetting()
          this.$message.success('修改菜品成功!')
        } else {
          this.$message.error('修改菜品失败!')
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    getAssessData (dishId) {
      // 点击查看评论，获取评论列表
      this.assess = true
      this.$request.post('/assess/getlist', {
        "dishId": dishId
      }).then((result) => {
        if (result.code === 200) {
          this.assessData = result.data
        } else {
          this.$message.error('获取评论列表失败!')
        }
      })
    },
    deleteAssess(orderId, dishId) {
      // 管理员删除评论
      if (confirm('确定要删除？')) {
        this.$request.post('/assess/admin/delete', {
          "orderId": orderId,
          "dishId": dishId
        }).then((result) => {
          if (result.code === 200 && result.data === 1) {
            this.getAssessData(dishId)
            this.getDishData()
            this.$message.success('删除评论成功!')
          } else {
            this.$message.error('删除评论失败!')
          }
        })
      }
    },
    deleteDish (dishId) {
      // 管理员删除菜品
      if (confirm('确定要删除？')) {
        this.$request.post('/dish/admin/delete', {
          "dishId": dishId
        }).then((result) => {
          if (result.code === 200 && result.data === 1) {
            this.resetting()
            this.$message.success('删除菜品成功!')
          } else {
            this.$message.error('删除菜品失败!')
          }
        })
      }
    },
    deleteType (typeId) {
      if (confirm('删除后与该类型绑定的菜品类型将变为未设置！确定要删除？')) {
        this.$request.post('/type/admin/delete', {
          "typeId": typeId
        }).then((result) => {
          if (result.code === 200 && result.data === 1) {
            this.getTypeData()
            this.getDishData()
            this.$message.success('删除菜品类型成功!')
          } else {
            this.$message.error('删除菜品类型失败!')
          }
        })
      }
    },
    addType () {
      if (this.addTypeName === '') {
        this.$message.error('请输入类型名!')
      } else {
        this.$request.post('/type/admin/add', {
          "typeName": this.addTypeName
        }).then((result) => {
          if (result.code === 200 && result.data === 1) {
            this.getTypeData()
            this.$message.success('添加菜品类型成功!')
          } else {
            this.$message.error('添加菜品类型失败!')
          }
        })
      }
      this.addTypeName = ''
    }
  }
}
</script>

<style scoped>
.table {
  width: 90%;
  font-size: small;
}
.new_dish{
  position: fixed;
  right: 60px;
  bottom: 50px;
  width: 40px;
  height:40px;
}
.edit_type{
  position: fixed;
  right: 60px;
  bottom: 100px;
  width: 40px;
  height:40px;
}
</style>
